package com.agu.config.ds;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * MyBatis基础配置
 *
 */
@Configuration
@MapperScan(basePackages={"com.agu.api2.*.dao"}, sqlSessionFactoryRef = "sqlSessionFactorySecond")
public class MyBatisSecondConfig {

	@Autowired
	@Qualifier("secondDataSource")
	private DataSource secondDataSource;

	@Primary
	@Bean("sqlSessionFactorySecond")
	public SqlSessionFactory sqlSessionFactorySecond() throws Exception {
		SqlSessionFactoryBean sqlsession = new SqlSessionFactoryBean();
		sqlsession.setDataSource(secondDataSource); // 连接second库
		
		// 扫描entity包 使用别名
		sqlsession.setTypeAliasesPackage("com.agu.entity");
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		// 使用jdbc的getGeneratedKeys获取数据库自增主键值
		configuration.setUseGeneratedKeys(true);
		// 使用列别名替换列名 select user as User
		configuration.setUseColumnLabel(true);
		// -自动使用驼峰命名属性映射字段 userId user_id
		configuration.setMapUnderscoreToCamelCase(true);
		sqlsession.setConfiguration(configuration);
		sqlsession.setFailFast(true);

		// 添加XML目录
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			Resource[] res = resolver.getResources("classpath*:mapper/api2/**/*.xml");
			sqlsession.setMapperLocations(res);
			return sqlsession.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	@Bean("sqlSessionTemplateSecond")
	public SqlSessionTemplate sqlSessionTemplateSecond(
			@Qualifier("sqlSessionFactorySecond") SqlSessionFactory springSecondSqlSessionFactory) {
		return new SqlSessionTemplate(springSecondSqlSessionFactory);
	}

}